package com.resoft.bigdata.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

public class DateUtil {
	// 短日期格式  
	 public static String DATE_FORMAT = "yyyy-MM-dd";
	 public static String DATE_FORMAT_SIMPLE = "yyyyMMdd";
	   
	 // 长日期格式  
	 public static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	 
	 private static long ONE_DAY = 1000*3600*24;
	   
	 /** 
	  * 将日期格式的字符串转换为长整型 
	  *  
	  * @param date 
	  * @param format 
	  * @return 
	  */  
	 public static long convert2long(String date, String format) {  
	  try {
		  if (StringUtils.isNotBlank(date)) {  
			 if (StringUtils.isBlank(format)){  
		    	SimpleDateFormat sf = null;
		    	try {
				    sf = new SimpleDateFormat(DateUtil.TIME_FORMAT);  
				    return sf.parse(date).getTime();
				} catch (Exception e) {
					sf = new SimpleDateFormat(DateUtil.DATE_FORMAT_SIMPLE);
					return sf.parse(date).getTime();
				}
		     }
		  }  
	  } catch (ParseException e) {  
		  e.printStackTrace();  
	  }  
	  return 0l;  
	 }  
	 
	 /** 
	  * 将日期格式的字符串转换为整型 
	  *  
	  * @param date 
	  * @param format 
	  * @return 
	  */  
	 public static int convert2Day(String date, String format) {  
	  try {  
		   if (StringUtils.isNotBlank(date)) {  
			   	SimpleDateFormat sf = null;
			    if (StringUtils.isBlank(format)){  
			    	format = DateUtil.TIME_FORMAT;  
			    }
			    try {
			    	sf = new SimpleDateFormat(format);
			    	return (int)(sf.parse(date).getTime()/ONE_DAY);
				} catch (Exception e) {
					sf = new SimpleDateFormat(DateUtil.DATE_FORMAT_SIMPLE);
					return (int)(sf.parse(date).getTime()/ONE_DAY);
				}
		   }  
	  } catch (ParseException e) {  
	   e.printStackTrace();  
	  }  
	  
	  return 0;  
	 } 
	 
	 public static int reverseDate(String dateString){
		 String format = "yyyyMMdd";
		 if(dateString.contains("/")){
			 format = "yyyy/MM/dd";
		 }else if(dateString.contains("-")){
			 format = "yyyy-MM-dd";
		 }
		 
		 int days = convert2Day(dateString, format);
		 
		 return Integer.MAX_VALUE - days;
		 
	 }
	   
	 /** 
	  * 将长整型数字转换为日期格式的字符串 
	  *  
	  * @param time 
	  * @param format 
	  * @return 
	  */  
	 public static String convert2String(long time, String format) {  
	  if (time > 0l) {  
	   if (StringUtils.isBlank(format))  
	    format = DateUtil.TIME_FORMAT;  
	   SimpleDateFormat sf = new SimpleDateFormat(format);  
	   Date date = new Date(time);  
	   return sf.format(date);  
	  }  
	  return "";  
	 }  
	 
	 
	 /**
	  * 
	  * @param dateString
	  * @return
	  */
	 public static String addOneDay(String dateString){
		 long ts = convert2long(dateString, null);
		 
		 return convert2String(ts + ONE_DAY, DATE_FORMAT);
	 }
	 
	 public static String addSomeDays(String dateString, int someDay){
		 long ts = convert2long(dateString, null);
		 
		 return convert2String(ts + someDay*ONE_DAY, DATE_FORMAT);
	 }
}
